import { SuccessModel, ErrorModel } from '../../../../utils/respond/ResModel';
import { CRYPTO_SECRET_KEY } from '../../../../config/index';
import { AdminUser } from '../models/userModel';
import md5 from 'md5';
import { Apis, Menus, Roles } from '../../system/models';
import { redis } from '../../../../loaders/loader-redies';
import { getCurrentTime } from '../../../../utils/time';
/**
 * 查询后台管理端是否存在
 * @param {userName，password} body
 */

const checkUser = async ({ account, password }) => {
  const user = await AdminUser.findOne({
    where: {
      account,
      password: md5(`${CRYPTO_SECRET_KEY}${password}`),
    },
  });
  if (user) {
    return user;
  }
  return null;
};

/**
 * 后台管理员登录
 * @param {userName，password} body
 */
export const adminLogin = async (body, ctx) => {
  try {
    const { account, password, captcha } = body;
    const sessionCaptcha = ctx.jwtSession.captcha;
    if (captcha.toLowerCase() !== sessionCaptcha.toLowerCase()) {
      return new ErrorModel({ message: '验证码错误' });
    }
    const user = await checkUser({ account, password });
    if (user) {
      if (user.status === 1102) {
        return new ErrorModel({ message: '账号已被禁用，请联系管理员' });
      } else {
        await AdminUser.update({ loginTime: getCurrentTime() }, { where: { id: user.id } });
        return new SuccessModel({
          data: '登录成功',
          token: ctx.setJwtSession(
            {
              userId: user.id,
              userName: user.userName,
              account: user.account,
              isAdmin: true, // 标识该用户是后台管理端的用户
            },
            60 * 60 * 12
          ),
        });
      }
    } else {
      return new ErrorModel({ message: '账号或密码错误' });
    }
  } catch (error) {
    console.log('error', error);
    return new ErrorModel({ message: '修改用户失败' });
  }
};

/**
 * 添加后台管理员
 * @param {account,userName，password,roleIds} body
 */
export const adminRegister = async (body) => {
  try {
    const { account, password, userName, avatar, status, roleIds } = body;
    const oldUser = await checkUser({ account, password });
    if (oldUser) {
      return new ErrorModel({ message: '用户已存在' });
    }
    const newUser = await AdminUser.create({
      account,
      password: md5(`${CRYPTO_SECRET_KEY}${password}`),
      userName,
      avatar,
      status,
    });
    if (roleIds && roleIds.length > 0) {
      // AdminUser
      const roles = await Roles.findAll({ where: { id: roleIds } });
      await newUser.setRoles(roles);
    }
    return new SuccessModel({ message: '注册成功' });
  } catch (error) {
    console.log('error', error);
  }
};

/**
 * 修改后台管理员
 * @param {userName,roleIds} body
 */
export const adminUpdate = async (body) => {
  try {
    const { id, userName, roleIds, status } = body;
    let updateResult = await AdminUser.update(
      { userName, status },
      {
        where: { id },
      }
    );
    if (updateResult && updateResult.length > 0) {
      const user = await AdminUser.findOne({ where: { id } });
      if (roleIds && roleIds.length > 0) {
        let roles = await Roles.findAll({ where: { id: roleIds } });
        user.setRoles(roles);
      } else {
        // 清除用户角色？
      }
      if (status === 1102) {
        // 如果禁用了用户，应该强制让用户掉线
        redis.expire(`user_expire_${id}`, 3);
      }
      return new SuccessModel({ data: '修改成功' });
    }
    return new ErrorModel({ message: '修改用户失败' });
  } catch (error) {
    console.log('error', error);
    return new ErrorModel({ message: '修改用户失败' });
  }
};

/**
 * 后台用户获取个人信息:[菜单，权限]
 */
export const getAdminInfo = async (userId) => {
  const userInfo = await AdminUser.findOne({
    where: {
      id: userId,
    },
    attributes: { exclude: ['password'] },
    include: [
      {
        model: Roles,
        through: {
          attributes: [],
        },
        include: [
          {
            model: Menus,
            through: {
              attributes: [],
            },
            include: [
              {
                model: Apis,
                through: {
                  attributes: [],
                },
              },
            ],
          },
        ],
      },
    ],
  });
  let prem = [];
  let menus = [];
  let apisStr = '|';
  if (userInfo && userInfo.roles) {
    const rolesList = userInfo.roles.filter((item) => item.status === 1101);
    rolesList.forEach((item) => {
      item.menus.forEach((menu) => {
        if (menu.type == 1101 || menu.type == 1102) {
          const { id, type, label, name, parentId, icon, hidden } = menu;
          menus.push({ id, type, label, name, parentId, icon, hidden });
        }
        if (menu.type == 1103 && menu.perm) {
          if (prem.indexOf(menu.perm) < 0) {
            prem.push(menu.perm);
          }
          menu.apis.forEach((api) => {
            if (apisStr.indexOf(`|${api.method}_${api.url}|`) < 0) {
              apisStr += `${api.method}_${api.url}|`;
            }
          });
        }
      });
    });
  }
  await redis.setString(`PERMISSION_APIS_${userId}`, apisStr);

  return new SuccessModel({
    data: {
      account: userInfo.account,
      userName: userInfo.userName,
      avatar: userInfo.avatar,
      prem,
      menus,
    },
  });
};

/**
 * 分页获取后台用户
 */
export const getAdminPage = async ({ page, size }) => {
  const result = await AdminUser.findAndCountAll({
    limit: size,
    offset: (page - 1) * size,
    include: [
      {
        model: Roles,
        through: {
          attributes: [],
        },
      },
    ],
  });
  return new SuccessModel({ data: result });
};
